package com.example.mybatisplusdemo.web.controller;


import com.example.mybatisplusdemo.common.Result;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.mapper.UserMapper;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;
    @PostMapping("/login")


    public Result login (@RequestBody User user) {
        List<User> userList1 = userService.query().eq("useraccount", user.getUseraccount()).
                eq("role_id", user.getRoleId()).list();//查找账号是否已注册

        if (!userList1.isEmpty()) {  //账号注册过
            //查找账号密码是否匹配
            List<User> userList2 = userService.query().eq("useraccount", user.getUseraccount()).
                    eq("userpsd", user.getUserpsd()).eq("role_id", user.getRoleId()).list();
            if (!userList2.isEmpty()) {   //账号密码一致
                SessionUtils.saveCurrentUserInfo(userList2.get(0));
                return Result.suc(user, 0L);
            } else {
                return Result.fail(401);  //code:401代表密码错误
            }
        } else {
            return Result.fail();   //默认code400：代表账号未注册
        }
    }
        @PostMapping("/register")
        public Result register (@RequestBody User user){
            System.out.println(user.toString());
            int roleId = user.getRoleId();
            String account = user.getUseraccount();
            List<User> userList = userService.query().eq("useraccount", account).
                    eq("role_id", roleId).list();
            if (roleId == 1 && userList.isEmpty()) {  //角色为用户且未注册过
//                int id = (int)userService.count();
//                user.setUserid(id + 1);
                userService.save(user);
                return Result.suc("用户注册成功", null, 0L);
            } else if (roleId == 2 && userList.isEmpty()) {  //角色为设计师且未注册过
//                int id = (int)userService.count();
//                user.setUserid(id + 1);
                userService.save(user);
                return Result.suc("设计师注册成功", null, 0L);
            } else {
                return Result.fail();
            }
        }



}
